package config;

import java.lang.reflect.Method;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport{
	
	@Autowired
	@Qualifier("cacheRedisTemplate")
	RedisTemplate<Object, Object> redisTemplate;
	
	@Bean
	public CacheManager cacheManager() {
	    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
	    //设置缓存过期时间 
	    cacheManager.setDefaultExpiration(3000);
	    return cacheManager;
	}
	 
	@Bean
	public KeyGenerator customKeyGenerator() {
		return new KeyGenerator() {
			public Object generate(Object target, Method method, Object... objects) {
	              StringBuilder sb = new StringBuilder();
	              sb.append(target.getClass().getName());
	              sb.append(method.getName());
	              for (Object obj : objects) {
	                  sb.append(obj.toString());
	              }
	              return sb.toString();
	         }
	    };
	}
	
}
